package com.wisdom.weld.service.impl;

import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.TypeRef;
import com.wisdom.weld.common.ConfigurationFactory;
import com.wisdom.weld.common.Generator;
import com.wisdom.weld.convert.JavaObjectConverter;
import com.wisdom.weld.convert.XMLObjectConverter;
import com.wisdom.weld.pojo.ClassAttribute;
import com.wisdom.weld.pojo.MapperXMLAttribute;
import com.wisdom.weld.pojo.TableAttribute;
import com.wisdom.weld.service.GeneratorService;
import com.wisdom.weld.util.IOUtils;
import com.wisdom.weld.util.JsonPathUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 通用Mapper的实现
 */
public class MybatisMapperGeneratorServiceImpl implements GeneratorService {
    @Override
    public void generate(List<TableAttribute> tableAttributes) {
        Configuration cfg = ConfigurationFactory.getConfiguration();
        List<ClassAttribute> classAttributes = JavaObjectConverter.convert(tableAttributes);
        try {
            DocumentContext context = JsonPathUtils.getContext();
            List<Generator.GenerateInfo> generateInfo = Generator.createMapperGenerateInfo();
            for (Generator.GenerateInfo info : generateInfo) {
                Template template = cfg.getTemplate(info.getTemplateName());
                for (ClassAttribute attribute : classAttributes) {
                    TypeRef<Map<String, String>> typeRef = new TypeRef<Map<String, String>>() {
                    };
                    Map<String, String> infoMap = context.read(info.getPath(), typeRef);
                    String dirPath = String.format("%s/%s/%s", System.getProperty("user.dir"), infoMap.get("targetProject"), infoMap.get("targetPackage").replace(".", "/"));
                    String fileName = String.format("%s%s", attribute.getClassName(), info.getSuffix());
                    FileWriter fileWriter = IOUtils.getFileWriter(dirPath, fileName);
                    template.process(attribute, fileWriter);
                }
            }
        } catch (IOException | TemplateException e) {
            throw new RuntimeException("生成代码异常", e);
        }
    }
}
